"""
异步迭代器示例
1.实现__aiter__ 和 __anext__ 方法的类,而普通迭代器是实现了 __iter__ 和 __next__ 方法的类
2.使用async for 循环遍历异步迭代器
"""

import asyncio


class AsyncIterator:
    def __init__(self, data):
        self.data = data
        self.index = 0

    def __aiter__(self):
        return self

    async def __anext__(self):

        if self.index >= len(self.data):
            raise StopAsyncIteration
        await asyncio.sleep(1)  # 模拟异步操作
        value = self.data[self.index]
        self.index += 1
        return value


async def main():
    async_iter = AsyncIterator([1, 2, 3, 4, 5])
    async for item in async_iter:
        print(item)


if __name__ == "__main__":
    asyncio.run(main())
